package com.steven.ourcontest.me.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.login.helper.LoginController
import com.steven.ourcontest.me.api.MeApi
import com.steven.ourcontest.me.bean.UsersDetailsRes
import com.steven.ourcontest.team.api.TeamApi
import com.steven.ourcontest.team.bean.TeamInfoRes
import com.steven.ourcontest.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import okhttp3.RequestBody
import java.lang.Exception

class MeViewModel : BaseViewModel() {
    private val _uploadRes = MutableLiveData<UsersDetailsRes?>()
    val uploadRes: LiveData<UsersDetailsRes?>
        get() = _uploadRes
    private val _userTeamResponse = MutableLiveData<TeamInfoRes?>()
    val userTeamResponse: LiveData<TeamInfoRes?>
        get() = _userTeamResponse

    fun uploadIcon(body: RequestBody) {
        if (!LoginController.isLogin) {
            return
        }
        disposed += MeApi.instance.uploadIcon(body)
            .flatMap {
                if (it.result?.msg == "success") {
                    return@flatMap MeApi.instance.querySelfUrl()
                } else {
                    throw Exception("上传失败")
                }
            }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _uploadRes.value = it.result
            }, {
                it.printStackTrace()
            })
    }

    fun queryUrl() {
        if (!LoginController.isLogin) {
            return
        }
        disposed += MeApi.instance.querySelfUrl()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                _uploadRes.value = it.result
            }, {
                it.printStackTrace()
            })
    }

    fun queryUserTeam(friendId: Long) {
        disposed += TeamApi.instance.queryUserTeam(friendId)
            .subscribe({
                _userTeamResponse.value = it
            }, {
                _userTeamResponse.value = null
                it.printStackTrace()
            })
    }
}